package easytalk.connectivity.googletalk;

import java.io.IOException;
import java.util.Date;

import org.apache.log4j.FileAppender;
import org.apache.log4j.Logger;
import org.apache.log4j.PatternLayout;
import org.jivesoftware.smack.Chat;
import org.jivesoftware.smack.MessageListener;
import org.jivesoftware.smack.packet.Message;

import common.Discussion;
import common.DiscussionSentence;
import common.EasyChatEnvironment;
import common.EasyTalkException;
import common.Locutor;
import common.DiscussionSentence.MessageType;

import easytalk.dialogs.ChatDialogManager;

public class GoogleTalkMessageListener implements MessageListener {

	Logger logger = Logger.getLogger(getClass());

	public GoogleTalkMessageListener() {
		FileAppender appender;

		try {
			appender = new FileAppender(new PatternLayout(), logger.getName()
					+ ".log");
			logger.addAppender(appender);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

	@Override
	public void processMessage(Chat arg0, Message arg1) {

		Locutor locutor;
		try {
			locutor = EasyChatEnvironment.getInstance().getLocutorById(
					arg1.getFrom(), new GoogleTalkIdComparator());
		} catch (EasyTalkException e) {
			e.printStackTrace();
			return;
		}

		for (Discussion dicussion : EasyChatEnvironment.getInstance()
				.FindDiscussionsWith(locutor)) {

			if (arg1.getBody() == null)
				dicussion.clearNotifications();
			DiscussionSentence sentence = dicussion.createSentence(locutor,
					arg1.getBody(), new Date(),
					(arg1.getBody() == null) ? MessageType.NOTIFICATION
							: MessageType.NORMAL);
			dicussion.getSentences().add(sentence);
			ChatDialogManager.getInstance().updateDiscussions(dicussion);

		}
	}

}
